#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

#include <gtk/gtk.h>

#include "callbacks.h"
#include "interface.h"
#include "support.h"
#include "debug.h"
#include "about.h"
#include "help.h"
#include "message.h"
#include <mysql.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
//GtkWidget *window_main;
//GtkWidget *window_addreader;
static MYSQL *conn;
void get_time(char *time_str)
{
	time_t timep;
	struct tm *p;
	time(&timep);
	p = gmtime(&timep);
	sprintf(time_str,"%d-%d-%d", (1900+p->tm_year), (1+p->tm_mon), p->tm_mday);
	return ;
}
void
on_menu_logout_activate                (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	debug_where();
}


void
on_menu_quit_activate                  (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	mysql_close(conn);
	debug_where();
	gtk_main_quit();
}


void
on_madd_reader_activate                (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	
	GtkWidget *window_addreader;
	window_addreader =  create_window3 ();
	gtk_widget_show(window_addreader);
	debug_where();
}


void
on_mdelete_reader_activate             (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	GtkWidget *window_delete_reader;
	window_delete_reader = create_window5();
	gtk_widget_show(window_delete_reader);
	debug_where();
}


void
on_madd_book_activate                  (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	 GtkWidget *window_add_book;
         window_add_book = create_window6();
	 gtk_widget_show(window_add_book);
	 debug_where();
}


void
on_mdelete_book_activate               (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	GtkWidget *window_delete_book;
	window_delete_book = create_window7();
	gtk_widget_show(window_delete_book);
	debug_where();
}


void
on_mback_borrow_activate               (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	GtkWidget *window_borrow_book;
	window_borrow_book = create_window9();
	gtk_widget_show(window_borrow_book);
	debug_where();
}
void
on_mback_back_activate                 (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	GtkWidget *window_back_book;	
	window_back_book = create_window10();
	gtk_widget_show(window_back_book);
	debug_where();
}


void
on_help_topic_activate                 (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	GtkWidget *window_help = create_window_help();
	gtk_widget_show(window_help);
	debug_where();
}


void
on_help_about_activate                 (GtkMenuItem     *menuitem,
                                        gpointer         user_data)
{
	GtkWidget *window_about = create_window_about();
	gtk_widget_show(window_about);
	debug_where();
}


void
on_button_help_clicked                 (GtkButton       *button,
                                        gpointer         user_data)
{
	GtkWidget *window_add_r = (GtkWidget *)user_data;
	char message[] = "以下信息均为字符格式，长度分别为：\n借书证号：20，姓名：15，单位：30，电话：15，密码：15";
	show_message(window_add_r, GTK_MESSAGE_INFO, message);
	debug_where();
}


void
on_button_ok_clicked                   (GtkButton       *button,
                                        gpointer         user_data)
{
	/* 注册读者信息，确定按钮处理 */
	const gchar *rname;
	const gchar *rnumber;
	const gchar *sex;
	const gchar *phone;
	const gchar *password;
	const gchar *department;
	char insertstr[512] = "\0";
	struct add_reader_struct *add_reader = (struct add_reader_struct *)user_data;
	rnumber = (const gchar *)gtk_entry_get_text(GTK_ENTRY(add_reader->entry_number));
	rname = (const gchar *)gtk_entry_get_text(GTK_ENTRY(add_reader->entry_name));
	phone = (const gchar *)gtk_entry_get_text(GTK_ENTRY(add_reader->entry_phone));
	password = (const gchar *)gtk_entry_get_text(GTK_ENTRY(add_reader->entry_password));
	sex = (const gchar *)gtk_entry_get_text(GTK_ENTRY(GTK_BIN(add_reader->com_sex)->child));
	department = (const gchar *)gtk_entry_get_text(GTK_ENTRY(add_reader->entry_department));
	debug_where();
	if (!strlen(rname) || !strlen(sex) ||!strlen(password)) {
		debug_print("error\n");
		char message[] = "姓名或者性别或者密码不能为空";
		show_message(add_reader->window_add_r, GTK_MESSAGE_INFO, message);
		return;
	}		
	if(strlen(rnumber) > 20) {
		char message[] = "借书证号长度最大值为20";
		show_message(add_reader->window_add_r, GTK_MESSAGE_INFO, message);
		return;
	}
	if(strlen(rname) > 15) {
		char message[] = "姓名长度最大值为15";
		show_message(add_reader->window_add_r, GTK_MESSAGE_INFO, message);
		return;
	}
	if(strlen(phone) > 15) {
		char message[] = "电话号码长度最大值为15";
		show_message(add_reader->window_add_r, GTK_MESSAGE_INFO, message);
		return;
	}
	if(strlen(department) > 30) {
		char message[] = "单位长度最大值为30";
		show_message(add_reader->window_add_r, GTK_MESSAGE_INFO, message);
		return;
	}
	if(strlen(password) > 15) {
		char message[] = "密码长度最大值为15";
		show_message(add_reader->window_add_r, GTK_MESSAGE_INFO, message);
		return;
	}
	sprintf(insertstr,"insert into reader values('%s','%s','%s','%s','%s','%s')",rnumber, rname, sex, department, phone, password);
	if (mysql_query(conn, insertstr)) {
		char message[] = "借书证号不能为空或者已存";
		show_message(add_reader->window_add_r, GTK_MESSAGE_INFO, message);
		return ;
	}
	show_message(add_reader->window_add_r, GTK_MESSAGE_INFO, "注册成功");
	gtk_widget_destroy(add_reader->window_add_r);
}


void
on_button_cancel_clicked               (GtkButton       *button,
                                        gpointer         user_data)
{
	struct add_reader_struct *add_reader = (struct add_reader_struct *)user_data;
	gtk_widget_destroy(add_reader->window_add_r);
	debug_where();
}

void
on_button_ok_dr_clicked                   (GtkButton       *button,      
		                                        gpointer         user_data)    
{
	struct del_reader_struct *del_reader = (struct del_reader_struct *)user_data;
	const gchar *rnumber;
	char deletestr[512];
	rnumber = (const gchar *)gtk_entry_get_text(GTK_ENTRY(del_reader->entry_rnumber));
	debug_where();
	debug_print("得到借书证号%s，删除从Mysql\n", rnumber);
	//返回结果
	sprintf(deletestr, "delete from reader where number='%s'", rnumber);
	if (mysql_query(conn, deletestr)) {
		show_message(del_reader->window_del_r, GTK_MESSAGE_INFO, "注销错误");
		return ;
	}
	if (!mysql_affected_rows(conn)) {
		show_message(del_reader->window_del_r, GTK_MESSAGE_INFO, "无此读者信息");
		return ;
	}
	sprintf(deletestr, "delete from borrow where rnumber='%s'", rnumber);
	if (mysql_query(conn, deletestr)) {
		show_message(del_reader->window_del_r, GTK_MESSAGE_INFO, "注销相关信息错误");
		return ;
	}
	show_message(del_reader->window_del_r, GTK_MESSAGE_INFO, "注销成功");
	gtk_widget_destroy(del_reader->window_del_r);
}


void
on_button_cancel_dr_clicked               (GtkButton       *button,
		                                        gpointer         user_data)
{
	struct del_reader_struct *del_reader = (struct del_reader_struct *)user_data;
	debug_where();
	gtk_widget_destroy(del_reader->window_del_r);
}

void
on_button_ok_ab_clicked                   (GtkButton       *button,      
		                                        gpointer         user_data)    
{
	struct add_book_struct *add_book = (struct add_book_struct *)user_data;
	/* 接受数据 */
	const gchar *bnum;
	const gchar *bname;
	const gchar *bauthor;
	const gchar *btype;
	const gchar *bpress;
	const gchar *btime;
	const gchar *blib;
	const gchar *bremain;
	const gchar *bborrow;
	int r,b;
	char insertbook[512];
	bnum = (const gchar *)gtk_entry_get_text(GTK_ENTRY(add_book->entry_bnumber));
	bname = (const gchar *)gtk_entry_get_text(GTK_ENTRY(add_book->entry_bname));
	bauthor = (const gchar *)gtk_entry_get_text(GTK_ENTRY(add_book->entry_author));
	btype = (const gchar *)gtk_entry_get_text(GTK_ENTRY(add_book->entry_type));
	bpress = (const gchar *)gtk_entry_get_text(GTK_ENTRY(add_book->entry_press));
	btime = (const gchar *)gtk_entry_get_text(GTK_ENTRY(add_book->entry_time));
	blib = (const gchar *)gtk_entry_get_text(GTK_ENTRY(GTK_BIN(add_book->com_lib)->child));
	bremain = (const gchar *)gtk_entry_get_text(GTK_ENTRY(add_book->entry_remain));
	bborrow = (const gchar *)gtk_entry_get_text(GTK_ENTRY(add_book->entry_borrow));
	r = atoi(bremain);
	b = atoi(bborrow);
	if(strlen(bnum) > 20 || !strlen(bnum)) {
		char message[] = "索引号长度最大值为20且不能为空";
		show_message(add_book->window_add_b, GTK_MESSAGE_INFO, message);
		return;
	}
	if(strlen(bname) > 20 || !strlen(bname)) {
		char message[] = "书名长度最大值为20且不能为空";
		show_message(add_book->window_add_b, GTK_MESSAGE_INFO, message);
		return;
	}
	if(strlen(btype) > 10) {
		char message[] = "书籍类型长度最大值为10";
		show_message(add_book->window_add_b, GTK_MESSAGE_INFO, message);
		return;
	}
	if(strlen(bauthor) > 30) {
		char message[] = "作者长度最大值为30";
		show_message(add_book->window_add_b, GTK_MESSAGE_INFO, message);
		return;
	}
	if(strlen(bpress) > 30) {
		char message[] = "出版社长度最大值为30";
		show_message(add_book->window_add_b, GTK_MESSAGE_INFO, message);
		return;
	}
	/* 处理数据 */
	sprintf(insertbook,"insert into book values('%s','%s','%s','%s','%s','%s','%s','%d','%d')",
		bnum, bname, btype, bauthor, bpress, btime, blib, r, b);
	if (mysql_query(conn, insertbook)) {
		char message[] = "注册错误";
		show_message(add_book->window_add_b, GTK_MESSAGE_INFO, message);
		return;
	}
	/* 返回结果 */
	debug_where();
	gtk_widget_destroy(add_book->window_add_b);
}


void
on_button_cancel_ab_clicked               (GtkButton       *button,
		                                        gpointer         user_data)
{
	struct add_book_struct *add_book = (struct add_book_struct *)user_data;
	debug_where();
	gtk_widget_destroy(add_book->window_add_b);
}

void
on_button_ok_db_clicked                   (GtkButton       *button,      
		                                        gpointer         user_data)    
{
	struct del_book_struct *del_book = (struct del_book_struct *)user_data;                
	/* 从数据库中删除书籍信息 */
	char deletestr[512];
	const gchar *bnumber;
	bnumber = (const gchar *)gtk_entry_get_text(GTK_ENTRY(del_book->entry_bnumber));
	if(!strlen(bnumber) || strlen(bnumber) >20) {
		char message[] = "索引号长度最大值为20且不能为空";
		show_message(del_book->window_del_b, GTK_MESSAGE_INFO, message);
		return;
	}
	sprintf(deletestr, "delete from book where bnumber='%s'", bnumber);
	if (mysql_query(conn, deletestr)) {
		show_message(del_book->window_del_b, GTK_MESSAGE_INFO, "注销错误");
		return ;
	}
	sprintf(deletestr, "delete from borrow where bnumber='%s'", bnumber);
	if (mysql_query(conn, deletestr)) {
		show_message(del_book->window_del_b, GTK_MESSAGE_INFO, "注销相关信息错误");
		return ;
	}
	if (!mysql_affected_rows(conn)) {
		show_message(del_book->window_del_b, GTK_MESSAGE_INFO, "无此书籍信息");
		return ;
	}
	show_message(del_book->window_del_b, GTK_MESSAGE_INFO, "注销成功");
	debug_where();
        gtk_widget_destroy(del_book->window_del_b);


}
void
on_button_cancel_db_clicked               (GtkButton       *button,
		                                        gpointer         user_data)

{
	 struct del_book_struct *del_book = (struct del_book_struct * )user_data;
	 gtk_widget_destroy(del_book->window_del_b);
	debug_where();
}

void
on_button_ok_bb_clicked                   (GtkButton       *button,      
		                                        gpointer         user_data)    
{//borrow book
	 struct bor_book_struct *bor_book = (struct bor_book_struct *)user_data;                                       
	 const gchar *rnumber;
	 const gchar *bnumber;
	 char local_time[12];
	 char insertborrow[512];
	 char updatestr[512];
	 MYSQL_RES *res1;
	 MYSQL_RES *res2;
	 MYSQL_ROW row;
	 int remain;
	 rnumber = gtk_entry_get_text(GTK_ENTRY(bor_book->entry_rnumber));
	 bnumber = gtk_entry_get_text(GTK_ENTRY(bor_book->entry_bnumber));
	 
	 if(!strlen(rnumber) || !strlen(bnumber) || strlen(rnumber) >20 || strlen(bnumber)>20) {
	 	show_message(bor_book->window_bor_b, GTK_MESSAGE_INFO, "不能为空且长度要小于20");
	 	return ;
	}
	debug_where();
//book is right?
	sprintf(insertborrow, "select remain from book where bnumber='%s'", bnumber);
	mysql_query(conn, insertborrow);
	res1 = mysql_store_result(conn);
	if (!mysql_num_rows(res1)) {
		show_message(bor_book->window_bor_b, GTK_MESSAGE_INFO, "无此书籍");
		debug_where();
		return ;
	} else {
		row = mysql_fetch_row(res1);
		debug_where();
		remain = atoi(&row[0][0]);
		if (remain <= 0) {
			show_message(bor_book->window_bor_b, GTK_MESSAGE_INFO, "此书已经被借完");
			debug_where();
			return ;
		}
	}
	debug_print("%s\n", insertborrow);
//reader is right?	
	sprintf(insertborrow, "select * from reader where number='%s'", rnumber);
	debug_print("%s\n", insertborrow);
	mysql_query(conn, insertborrow);
	res2 = mysql_store_result(conn);
	if (!mysql_num_rows(res2)) {
		show_message(bor_book->window_bor_b, GTK_MESSAGE_INFO, "无此读者");
		debug_where();
		return ;
	}
	
	get_time(local_time);
	sprintf(insertborrow, "insert into borrow values('%s','%s','%s')", bnumber, rnumber,local_time);
	debug_print("insert:%s\n", insertborrow);
	if (mysql_query(conn, insertborrow)) {
		show_message(bor_book->window_bor_b, GTK_MESSAGE_ERROR, "借阅错误被重复借阅");
		debug_where();
		return ;
	}
	sprintf(updatestr, "update book set remain=remain-1, borrowed=borrowed+1 where bnumber='%s'",bnumber);
	if (mysql_query(conn, updatestr)) {
		show_message(bor_book->window_bor_b, GTK_MESSAGE_ERROR, "同步更新错误");
		debug_where();
		return ;
	}
	mysql_free_result(res1);
	mysql_free_result(res2);
	gtk_widget_destroy(bor_book->window_bor_b);
}


void
on_button_cancel_bb_clicked               (GtkButton       *button,
		                                        gpointer         user_data)
{
	 struct bor_book_struct *bor_book = (struct bor_book_struct *)user_data;                                     
	 debug_where();
	 gtk_widget_destroy(bor_book->window_bor_b);
}

void
on_button_ok_rb_clicked                   (GtkButton       *button,      
		                                        gpointer         user_data)    
{
	struct bac_book_struct *bac_book = (struct bac_book_struct *)user_data;                                   
	const gchar *bnumber;
	char rebackstr[512];
	
	bnumber = gtk_entry_get_text(GTK_ENTRY(bac_book->entry_bnumber));
	
	if (!strlen(bnumber) || strlen(bnumber) > 20) {
		char message[] = "索引号长度最大值为20且不能为空";
		show_message(bac_book->window_bac_b, GTK_MESSAGE_INFO, message);
		return;
	}
	
	sprintf(rebackstr, "delete from borrow where bnumber='%s'",bnumber);
	if (mysql_query(conn, rebackstr)) {
		show_message(bac_book->window_bac_b, GTK_MESSAGE_ERROR, "还书出现错误");
		debug_where();
		return ;
	}
	if (!mysql_affected_rows(conn)) {
		show_message(bac_book->window_bac_b, GTK_MESSAGE_INFO, "无此书籍信息");
		return ;
	}
	
	sprintf(rebackstr, "update book set remain=remain+1,borrower=borrowed+1 where bnumber='%s'", bnumber);
	if (mysql_query(conn, rebackstr)) {
		show_message(bac_book->window_bac_b, GTK_MESSAGE_ERROR, "同步更新错误");
		debug_where();
		return ;
	}
	show_message(bac_book->window_bac_b, GTK_MESSAGE_INFO, "还书成功");
	debug_where();
	gtk_widget_destroy(bac_book->window_bac_b);

}


void
on_button_cancel_rb_clicked               (GtkButton       *button,
		                                        gpointer         user_data)
{
	 struct bac_book_struct *bac_book = (struct bac_book_struct *)user_data;                                   
	 gtk_widget_destroy(bac_book->window_bac_b);
	 debug_where();
}


void
on_login_clicked                       (GtkButton       *button,
                                        gpointer         user_data)
{
	GtkWidget *window_main;
	char *server = "localhost";
	char *database = "managebook";
	struct login_struct *login = (struct login_struct *)user_data;
	const gchar *usename;
	const gchar *password;
	usename = (const gchar *)gtk_entry_get_text(GTK_ENTRY
			(login->entry_usename));
	password = (const gchar *)gtk_entry_get_text
		(GTK_ENTRY(login->entry_password));
	conn = mysql_init(NULL);
	if (!mysql_real_connect(conn,server,usename,password,
				database,0,NULL,0)) {
		show_message(login->window_login, GTK_MESSAGE_INFO, "没有连接到数据库登录失败");
		exit(1);
	}
	
	gtk_widget_destroy(login->window_login);
	window_main =  create_window1 ();
	gtk_widget_show (window_main);
	debug_where();
}
void
on_button_find_clicked                 (GtkButton       *button,
                                        gpointer         user_data)
{
	struct main_info_struct *main_info = (struct main_info_struct *)user_data;
	const char *rnumber;
	char find_sql[256];
	char *clist_res[3];
	int i = 0;
	MYSQL_ROW row;
	MYSQL_RES *res;

	rnumber = gtk_entry_get_text(GTK_ENTRY(main_info->entry_rnumber));
	debug_print("%s\n", rnumber);
	
	snprintf(find_sql, 256, "select * from reader where number='%s'", rnumber);
	if (mysql_query(conn, find_sql)) {
		show_message(main_info->main_window, GTK_MESSAGE_ERROR, "系统错误：数据查找错误");
		return ;
	}
	res = mysql_store_result(conn);
	if ((row = mysql_fetch_row(res)) != NULL) {
		debug_print("%s, %s, %s, %s\n", row[1], row[2], row[3],
				row[4]);
		gtk_entry_set_text(GTK_ENTRY(main_info->entry_rname), 
				row[1]);
		gtk_entry_set_text(GTK_ENTRY(main_info->entry_sex), 
				row[2]);
		gtk_entry_set_text(GTK_ENTRY(main_info->entry_department), 
				row[3]);
		gtk_entry_set_text(GTK_ENTRY(main_info->entry_phone), 
				row[4]);
	} else {
		show_message(main_info->main_window, GTK_MESSAGE_INFO, "无此读者信息");
		return ;
	}

	snprintf(find_sql, 256, "select bname, borrow.bnumber,reback \
			from borrow,book where borrow.bnumber=book.bnumber and rnumber='%s'",
			rnumber);
	if (mysql_query(conn, find_sql)) {
		show_message(main_info->main_window, GTK_MESSAGE_ERROR, "系统错误：数据查找错误");
		return ;
	}
	res = mysql_store_result(conn);
	while ((row = mysql_fetch_row(res)) != NULL) {
		for(i=0; i<3; i++) clist_res[i] = row[i];
		gtk_clist_append(GTK_CLIST(main_info->clist_borrow), clist_res);
	}
	debug_where();
}


void
on_button_clear_clicked                (GtkButton       *button,
                                        gpointer         user_data)
{
	debug_where();
	struct main_info_struct *main_info = (struct main_info_struct *)user_data;
	gtk_entry_set_text(GTK_ENTRY(main_info->entry_rnumber), "");
	gtk_entry_set_text(GTK_ENTRY(main_info->entry_rname), "");
	gtk_entry_set_text(GTK_ENTRY(main_info->entry_sex), "");
	gtk_entry_set_text(GTK_ENTRY(main_info->entry_department), "");
	gtk_entry_set_text(GTK_ENTRY(main_info->entry_phone), "");
	gtk_clist_clear(GTK_CLIST(main_info->clist_borrow));
}
